package com.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;


public class FreemarkerFilter implements Filter{
	private FilterConfig filterConfig;
	public void destroy() {
		
		
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String str = "/Test404/index.html";//request.getRequestURI().toString(); 
		String separator = "/Test404";//request.getContextPath();
		//int pos = str.indexOf(separator);
        
        //str.substring(pos + separator.length());
		String filePath = StringUtils.substringAfter(str, separator);
		System.err.println("**************"+filePath);
		long start = System.currentTimeMillis();
		System.err.println("*************测试 freemarker 处理页面****");
		FreemarkerEngine  freemarkerEngine = FreemarkerEngine.getInstance(filterConfig.getServletContext());
		try {
			Map<String,String> param = getParameter(request);
			freemarkerEngine.process(param,filePath, response);
			long end = System.currentTimeMillis();
			System.err.println("Freemarker Engine end***cost "+(end-start)+" ms");
			return;
		} catch (Exception e) {
			System.err.println("***错误****");
			filterChain.doFilter(servletRequest, servletResponse);
		}
		
	}

	public void init(FilterConfig arg0) throws ServletException {
		this.filterConfig = filterConfig;
		
	}
	@SuppressWarnings("unchecked")
	private Map<String,String> getParameter(HttpServletRequest request){
		Enumeration<String> enumeration = request.getParameterNames();
		Map<String,String> param = new HashMap<String,String>();
		while (enumeration.hasMoreElements()) {
			String key = enumeration.nextElement();
			String value = request.getParameter(key);
			param.put(key, value);
		}
		return param;
	}
}
